package com.blog.effective.note2;

/**
 * @func 使用构建器（Builder）
 * Created by 张俊强~ on 2017/10/30.
 */

public class UserInfo {

    private final String userId;        //required
    private final String userName;      //required
    private final String userPosition;
    private final String userSex;
    private final String userAge;
    private final String userEmail;

    public static class Builder {
        private final String userId;        //required
        private final String userName;      //required

        private String userPosition = "";
        private String userSex = "";
        private String userAge = "";
        private String userEmail = "";

        public Builder setUserEmail(String email) {
            userEmail = email;
            return this;
        }

        public Builder setUserSexAndPosition(String sex, String position) {

            //出现性别不是[男]的[Java程序员]，则抛异常
            if ((!"男".equals(sex)) && "Java程序员".equals(position)) {
                throw new RuntimeException("参数匹配异常");
            }
            userSex = sex;
            userPosition = position;
            return this;
        }


        public Builder setUserAge(String age) {
            userAge = age;
            return this;
        }

        public Builder(String userId, String userName) {
            this.userId = userId;
            this.userName = userName;
        }
        //最后的 build 方法
        public UserInfo build(){
            return new UserInfo(this);
        }

    }

    public UserInfo(Builder builder) {
        this.userId=builder.userId;
        this.userName=builder.userName;
        this.userPosition=builder.userPosition;
        this.userAge = builder.userAge;
        this.userEmail = builder.userEmail;
        this.userSex = builder.userSex;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                ", userPosition='" + userPosition + '\'' +
                ", userSex='" + userSex + '\'' +
                ", userAge='" + userAge + '\'' +
                ", userEmail='" + userEmail + '\'' +
                '}';
    }
}